<?php

namespace app\index;

use think\Controller;

class BaseController extends Controller
{
    public function validateOrError($sceneName = null, $className = null)
    {
        // 自动获取类名和场景名
        if ($className === null) {
            $currentClassName = get_class($this);
            $className = str_replace('controller', 'validate', $currentClassName);
        }
        if ($sceneName === null) {
            $sceneName = request()->action(true);
        }

        // 执行验证
        $result = $this->validate(
            input(),
            $className . '.' . $sceneName
        );

        // 抛出错误
        if ($result !== true) {
            error($result, 422);
        }
    }
}
